import React, { ReactElement, useEffect, useState } from 'react';
import { Animated, Easing, View } from 'react-native';

import { phonePx } from '../../../../util/adapt';
import styles from './style';

interface RippleProps {
  recording: boolean;
}

interface Line {
  initAnimate: Animated.Value;
  animate: Animated.AnimatedInterpolation;
}

export default ({ recording }: RippleProps): ReactElement => {
  const [lines, setLines] = useState<Line[]>([]);

  useEffect((): void => {
    if (!recording) {
      setLines([]);
      return;
    }
    const localLines: Line[] = [];
    for (let i = 0; i < 34; i += 1) {
      const initAnimate: Animated.Value = new Animated.Value(0);
      const animate = initAnimate.interpolate({
        inputRange: [0, 0.1, 0.2, 0.3, 0.5, 0.7, 0.8, 0.9, 1], // 输入值
        outputRange: [
          phonePx(10),
          phonePx(15),
          phonePx(21),
          phonePx(26),
          phonePx(32),
          phonePx(26),
          phonePx(21),
          phonePx(15),
          phonePx(10)
        ] // 输出值
      });

      localLines.push({ initAnimate, animate });
    }
    setLines(localLines);
  }, [recording]);

  useEffect((): (() => void) => {
    if (!recording) return (): void => {};
    const animations = lines.map(
      (item): Animated.CompositeAnimation =>
        Animated.loop(
          Animated.timing(item.initAnimate, {
            toValue: 1,
            duration: 1500,
            easing: Easing.bounce,
            useNativeDriver: false
          })
        )
    );
    const timer = Animated.stagger(200, animations);
    timer.start();

    return (): void => {
      timer.stop();
    };
  }, [lines, recording]);
  return (
    <View style={styles.lineContent}>
      {recording
        ? lines.map(
            (item): ReactElement => (
              <Animated.View style={[styles.line, { height: item.animate }]} />
            )
          )
        : new Array(34)
            .fill('')
            .map(
              (): ReactElement => (
                <View style={[styles.line, { height: phonePx(10) }]} />
              )
            )}
    </View>
  );
};
